package linkedlist;

/**
 * @description: <a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=featured-list&envId=2cktkvj?envType=featured-list&envId=2cktkvj">19. 删除链表的倒数第 N 个结点</a>
 * @author: zhaoyinglin
 * @date: 2024/3/5
 */
public class RemoveNthFromEnd {

    public static void main(String[] args) {
        int[] nums = new int[] { 1 };
        ListNode head = ListNode.generateLinkedList(nums);

        Solution solution = new Solution();

        System.out.println(solution.removeNthFromEnd(head, 1));

    }

    static class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null || n == 0) {
                return head;
            }
            ListNode cur = head;
            int len = 0;
            while (cur != null) {
                len++;
                cur = cur.next;
            }

            System.out.println("len = " + len);

            int count = 1;

            int k = len - n + 1;

            cur = head;

            ListNode lastNode = null;

            while (count != k) {
                count++;
                lastNode = cur;
                cur = cur.next;
            }

            if (lastNode == null) {
                head = cur.next;
            } else {
                lastNode.next = cur.next;
            }


            return head;
        }
    }
}
